package com.itheima.ssm.controller;


import com.itheima.ssm.domain.Permission;
import com.itheima.ssm.domain.Role;
import com.itheima.ssm.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService iRoleService;

//    添加权限方法
    @RequestMapping("/addPermissionToRole.do")
    public String addPermissionToRole(
            @RequestParam(name = "roleId",required = true)int roleId,
            @RequestParam(name = "ids",required = true)int[] permissionIds
    )throws Exception{
        iRoleService.addPermissionToRole(roleId,permissionIds);
        return "redirect:findAll.do";
    }

    @RequestMapping("/findRoleByIdPermission.do")
    public ModelAndView findRoleByIdPermission(
            @RequestParam(name = "id",required = true) int roleId
    )throws Exception{
        ModelAndView mv = new ModelAndView();
//        1.先通过id去查role的全部
       Role role = iRoleService.findById(roleId);
//        2.然后通过roleId主键去查权限
       List<Permission> permissions = iRoleService.findOtherPermission(roleId);
        mv.addObject("role",role);
        mv.addObject("permissionList",permissions);
        mv.setViewName("role-permission-add");
        return mv;
    }


    @RequestMapping("/findAll.do")
    public ModelAndView findAll() throws Exception {
        ModelAndView mv = new ModelAndView();
        List<Role> roles = iRoleService.findAll();
        mv.addObject("roleList",roles);
        mv.setViewName("role-list");
        return mv;
    }

    @RequestMapping("/save.do")
    public String save(Role role) throws Exception {
       iRoleService.save(role);
       return "redirect:findAll.do";
    }
}
